package top.haijunit.springboot.bucket.springsecurity02.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.haijunit.mark.common.core.Result;
import top.haijunit.springboot.bucket.springsecurity02.entity.UserEntity;
import top.haijunit.springboot.bucket.springsecurity02.service.UserService;

import java.util.List;
import java.util.Optional;

/**
 * @Author 百旺张
 * @Date 2021/11/11
 * @Description
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/user")
public class UserController {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;

    @PostMapping
    public Result<String> addEntity() {
        UserEntity dbUser = new UserEntity();
        dbUser.setUsername("user" + System.currentTimeMillis());
        dbUser.setPassword(passwordEncoder.encode("a"));
        dbUser.setNickname("用户" + System.currentTimeMillis());
        if (userService.save(dbUser)) {
            return Result.ok("添加用户成功");
        } else {
            return Result.failed("添加用户失败");
        }
    }

    @GetMapping("/list")
    public List<UserEntity> getList() {
        return userService.list();
    }

    @GetMapping
    public Result getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Optional.ofNullable(authentication).isPresent()) {
            return Result.ok().addData("username", authentication.getName()).addData("detail",authentication.getDetails());
        }
        return Result.failed("当前没有登录，无法获取登录用户");
    }
}
